import * as Parse from "parse"
(Parse as any).serverURL = "http://metapunk.cn:9999/parse"
Parse.initialize("dev")

/**
 * 列表
 * @param table 表名
 * @param params 查询参数
 * @param limit 记录条数
 * @returns result
 */
export function list(table: string, params: any = null, limit: number = -1): Promise<any> {
    return new Promise<any>(async (resolve: any, reject: any) => {
        const query = new Parse.Query(table)
        if (limit !== -1) {  // 记录数拼接
            query.limit(limit)
        }
        if (params !== null) {  // 条件拼接
            for (let param in params) {
                query.equalTo(param, params[param])
            }
        }
        const result: any = await query.find()
        if (result === undefined || result === null) {
            reject("error")
        }
        resolve(result.map((item: any) => item.toJSON()))
    })
}

/**
 * 获取一个
 * @param table 表名
 * @param params 参数
 * @returns result
 * 
 * getOne(表明, {
 *      name: “doufu”
 * })
 * 
 */
export function getOne(table: string, params: any = null): Promise<any> {
    return new Promise<any>(async (resolve: any, reject: any) => {
        list(table, params).then(res => {
            if (res.length === 0) {
                resolve(null)
            }
            resolve(res[0])
        }).catch(e => {
            reject(e)
        })
    })
}

/**
 * 新增
 * @param table 表名 
 * @param data 对象
 * @returns result
 * 
 * insert(biaming, {
 *  name: "123",
 * })
 */
export function insert(table: string, data: any): Promise<any> {
    const Record = Parse.Object.extend(table)
    const record = new Record()
    for (let item in data) {
        record.set(item, data[item])
    }
    return record.save()
}

/**
 * 修改
 * @param table 表名
 * @param data 对象
 * @returns result
 * 
 * // 修改 objectId = 123 的 name  = 阿松大
 * update(表名, {
 *      // 。。。
 *      name: 阿松大
 * }, 123)
 * 
 */
export function update(table: string, data: any, id: string = ""): Promise<any> {
    const query = new Parse.Query(table)
    if (id === "" && "id" in data) {
        id = data.id;
    }
    query.get(id).then(record => {
        for (let item in data) {
            if (item !== undefined || item !== null) {
                record.set(item, data[item])
            }
        }
        return record.save()
    })
    return new Promise<any>((resolve: any, reject: any) => reject())
}

/**
 * 删除
 * @param table 表名
 * @param id id
 * @returns result
 * 
 * biaoming, objectId
 * 
 */
export function remove(table: string, id: string): Promise<any> {
    const query = new Parse.Query(table)
    query.get(id).then(res => {
        return res.destroy()
    })
    return new Promise<any>((resolve: any, reject: any) => reject())
}
